package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
@RequiredArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private static final int BATCH_COUNT = 5;
    private final List<ExcelDictDTO> list = new ArrayList<>();
    private final DictMapper dictMapper;

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {
        log.debug("解析到数据: {}", data);
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!CollectionUtils.isEmpty(list)) {
            saveData();
            log.info("所有数据已持久化完毕");
        }
    }

    private void saveData() {
        if (CollectionUtils.isEmpty(list)) {
            log.warn("数据集合为空，跳过持久化操作");
            return;
        }

        log.info("准备持久化 {} 条字典数据", list.size());
        long startTime = System.currentTimeMillis();

        List<Dict> entityList = new ArrayList<>(list.size());
        for (ExcelDictDTO dto : list) {
            Dict entity = new Dict();
            BeanUtils.copyProperties(dto, entity);
            entityList.add(entity);
        }

        try {
            // 使用批量插入替代循环单条插入
            for (Dict dict : entityList) {
                dictMapper.insert(dict);
            }
            log.info("批量插入完成，耗时 {}ms", System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.error("数据持久化失败", e);
            throw new BusinessException("数据持久化失败");
        }
    }


}
